//
//  NewsFeedViewController.m
//  Mecca
//
//  Created by Ryan Enguero on 6/3/14.
//  Copyright (c) 2014 TapDash Heuristics. All rights reserved.
//

#import "NewsFeedViewController.h"

#import "PostClass.h"

#import "Constant.h"

#import "ParserClass.h"

#import "NewsFeedTableViewCell.h"

#import "NewsFeed.h"

#import "JsonClass.h"

#import "UIManager.h"

#import "Reachability.h"

#import "RotationTabViewController.h"

#import "NewsFeedContentViewController.h"

#import "FTWAPI.h"


@interface NewsFeedViewController (){

    FTWAPI *ftwApi;
    
    NSArray *searchResults;
}

@end

@implementation NewsFeedViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
      //  self.title = NSLocalizedString(@"Newsfeed", @"Newsfeed");
        
    }
    return self;
}



- (void)viewDidLoad
{
    [super viewDidLoad];
    //[self.navigationController.navigationBar setHidden:YES];
    
    
    if (!ftwApi) {
        ftwApi = [FTWAPI sharedInstance];
    }
    
    [self setupPullToRefresh];
    
    [self.navigationController setNavigationBarHidden:YES];
    
}

-(void)setupPullToRefresh
{

    UITableViewController *tableViewController = [[UITableViewController alloc] init];
    tableViewController.tableView = self.tableView;
    
    _refreshControll = [[UIRefreshControl alloc] init];
    _refreshControll.tintColor = [UIColor redColor];
    //    refresh.attributedTitle = [[NSAttributedString alloc] initWithString:@"Pull to Refresh"];
    [_refreshControll addTarget:self action:@selector(refreshTable) forControlEvents:UIControlEventValueChanged];
    tableViewController.refreshControl = _refreshControll;
}

-(void)refreshTable{
    
    [self.tableView reloadData];
    
    
}



-(void)viewWillAppear:(BOOL)animated{

    [self.tableView setBackgroundColor:[UIColor colorWithRed:33/255.0 green:33/255.0 blue:33/255.0 alpha:1.0]];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"notificationName" object:@"newsfeed"];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"cancelArtistFeeds" object:@"cancelArtist"];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(somethingHappens:) name:@"cancelNewsFeed" object:nil];
    
    self.receivedData = [NSMutableData data];
    NSURLRequest *request = [[PostClass sharedItems] getNewsfeed:[UIDevice currentDevice].identifierForVendor.UUIDString];
    _theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
    

}

-(void) somethingHappens:(NSNotification*) notification
{
    NSLog(@"notification = %@",[notification object]);
    
//    if ([[notification object] isEqualToString:@""]) {
//        
//    }
    [self.theConnection cancel];
}

-(void)userProfile{
    NSLog(@"User Profile");
    [[UIManager sharedItems]openLeft];
    [self.search resignFirstResponder];
    
}

- (IBAction)userProfileAction:(id)sender{

    NSLog(@"User Profile");
    [[UIManager sharedItems]openLeft];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //#warning Incomplete method implementation.
    // Return the number of rows in the section.
    
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        return [searchResults count];
        
    } else {
        return [[[ParserClass sharedItems] newsFeeds] count];
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    if ([_refreshControll isRefreshing]) {
        [_refreshControll endRefreshing];
    }
    
    // Configure the cell...
    
    static NSString *cellIdentifier = @"Cell";
    
    NewsFeedTableViewCell *cell = (NewsFeedTableViewCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    
    if (cell == nil) {
        
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"NewsFeedTableViewCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }
    
    NewsFeed *newsFeeds;
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        newsFeeds = [searchResults objectAtIndex:indexPath.row];
    } else {
        newsFeeds = [[[ParserClass sharedItems] newsFeeds] objectAtIndex:indexPath.row];
    }
    
    
    cell.titleLbl.text = [newsFeeds articleTitle];
    
    
    @autoreleasepool {
        
        
        [cell.newsFeedImg setAlpha:0];
        
        [UIView animateWithDuration:0.5 animations:^{
            
            NSString *imageUrl = [NSString stringWithFormat:@"http://192.185.93.102/~boomeran/backend-panel/%@", [newsFeeds articleImg]];
            
            [ftwApi setupCoverImage:cell.newsFeedImg withURL:imageUrl];
            [cell.activityView setHidden:YES];
            [cell.newsFeedImg setAlpha:1];
        } completion:^(BOOL finished) {
            
        }];
        
    }
    
    
    
    cell.dateLbl.text = [newsFeeds dateTracked];
    cell.descLbl.text = [newsFeeds description];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    
    
    
    return cell;
}


#pragma mark - Table view delegate

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSLog(@"Index Path Selected = %i", indexPath.row);
    
    NewsFeed *newsFeedData = [[ParserClass sharedItems]newsFeeds][indexPath.row];
    
    [UIManager sharedItems].newsFeedContentView = [[NewsFeedContentViewController alloc]initWithNibName:@"NewsFeedContentViewController" bundle:nil];
    
    NSArray *arrData = [[NSArray alloc] initWithObjects:[newsFeedData articleID],[newsFeedData articleTitle], [newsFeedData articleImg], [newsFeedData description], [newsFeedData dateTracked], nil];
    
    self.delegate = [UIManager sharedItems].newsFeedContentView;
    
    [self.delegate getData:arrData];
    
    [self.navigationController pushViewController:[UIManager sharedItems].newsFeedContentView animated:YES];
 
}

- (void)viewDidUnload{
    
    [super viewDidUnload];

    [[ParserClass sharedItems] emptyNewsFeed];
}

- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
    
    NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"dateTracked contains[c] %@", searchText];
    searchResults = [[[ParserClass sharedItems] newsFeeds] filteredArrayUsingPredicate:resultPredicate];
    
}

-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    [self filterContentForSearchText:searchString
                               scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
                                      objectAtIndex:[self.searchDisplayController.searchBar
                                                     selectedScopeButtonIndex]]];
    //[self.tableView reloadData];
    NSLog(@"Searching = %@", searchString);
    
    return YES;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 166;
}


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [_receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"Error data = %@", error);
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    
    
    if (connection == self.theConnection) {
        
        [_receivedData appendData:data];
        
        //  NSLog(@"data parse = %@", _receivedData);
        
    }
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    
    if (connection == self.theConnection) {
        
        if (!(_receivedData == nil)) {
            
            NSLog(@"Count Confirmed");
        
            NSMutableDictionary *json = [JsonClass jsonParser:_receivedData];
            
            [[ParserClass sharedItems] newsFeedDetails:json];
            
            [self.tableView reloadData];
            
            NSLog(@"newsFeed = %@", json);
            
        }
        
        
        NSLog(@"Finish");
    }
    
}


- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {

//    
//    if (self.view.frame.size.height == 568) {
//        
//        [UIView animateWithDuration:0.0f delay:0.0 options:UIViewAnimationOptionTransitionNone
//                         animations:^{
//                             self.scroller.contentOffset = CGPointMake(0, 30);
//                             self.banner.frame = (CGRectMake(self.banner.frame.origin.x, self.banner.frame.origin.y - 54, self.banner.frame.size.width, self.banner.frame.size.height));
//                         }
//                         completion:nil
//         ];
//    }else{
//        
//        [UIView animateWithDuration:0.0f delay:0.0 options:UIViewAnimationOptionTransitionNone
//                         animations:^{
//                             self.scroller.contentOffset = CGPointMake(0, 180);
//                             self.banner.frame = (CGRectMake(self.banner.frame.origin.x, self.banner.frame.origin.y - 54, self.banner.frame.size.width, self.banner.frame.size.height));
//                         }
//                         completion:nil
//         ];
//    }
    
    NSLog(@"Start");
    
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {

    
    
//    if (self.view.frame.size.height == 568) {
//        
//        [UIView animateWithDuration:0.0f delay:0.0 options:UIViewAnimationOptionTransitionNone
//                         animations:^{
//                             self.scroller.contentOffset = CGPointMake(0, 0);
//                             self.banner.frame = (CGRectMake(self.banner.frame.origin.x, self.banner.frame.origin.y + 54, self.banner.frame.size.width, self.banner.frame.size.height));
//                         }
//                         completion:nil
//         ];
//        
//    }else{
//        [UIView animateWithDuration:0.0f delay:0.0 options:UIViewAnimationOptionTransitionNone
//                         animations:^{
//                             self.scroller.contentOffset = CGPointMake(0, 0);
//                             self.banner.frame = (CGRectMake(self.banner.frame.origin.x, self.banner.frame.origin.y + 54, self.banner.frame.size.width, self.banner.frame.size.height));
//                         }
//                         completion:nil
//         ];
//    }
    
    NSLog(@"Stop");
}

- (void)searchDisplayController:(UISearchDisplayController *)controller didLoadSearchResultsTableView:(UITableView *)tableView {
    tableView.backgroundColor = [UIColor blackColor];
    
    [tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];

}

@end
